package reflect;

import java.io.File;
import java.net.URISyntaxException;
import java.util.Objects;

/**
 * 利用反射机制实例化reflect包下的所有类的对象
 * */
public class ReflectInstanceObject2 {
    /**
     * 类名.class.getResource(".")表示该类（字节码文件）所在的路径
     * */
    public static void main(String[] args) throws URISyntaxException, ClassNotFoundException,
            InstantiationException, IllegalAccessException {
        String s = "\n------------------------------------------------------------------------------\n";
        test1();
        System.out.print(s);
    }

    /** 创建reflect包下的所有类的实例 */
    public static void test1() throws URISyntaxException, ClassNotFoundException,
            InstantiationException, IllegalAccessException {
        File dir = new File(Objects.requireNonNull(
                ReflectInstanceObject2.class.getResource(".")       // 当前类所在的目录
        ).toURI());
        System.out.println(dir.getAbsolutePath());
        String packageName = dir.getName();     // 包名
        File[] files = dir.listFiles(f -> f.getName().endsWith(".class"));
        for (File classfile : files) {
            String className = packageName + "." + classfile.getName().split("\\.")[0];
            Class<?> c = Class.forName(className);
            Object obj = c.newInstance();
            System.out.println(obj);
        }
    }
}
